import { patientSearch } from '@/services/PatientService';
import {
  deleteRecordFile,
  videoRecordList,
} from '@/services/VideoRecordService';
import { RecordFile } from '@/types';
import { useModel } from '@@/exports';
import {
  DeleteOutlined,
  DownloadOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import {
  ProFormDateRangePicker,
  ProFormItem,
  ProFormRadio,
  QueryFilter,
} from '@ant-design/pro-form';
import {
  Button,
  Col,
  Image,
  Popconfirm,
  Row,
  Select,
  SelectProps,
  message,
} from 'antd';
import { parse } from 'query-string';
import { useEffect, useState } from 'react';
import { isBlank } from 'web-plugin-utils';
import styles from './index.less';

const PatientSearch = ({
  peerServer,
  placeholder,
  ...rest
}: {
  placeholder: string;
  peerServer: string;
  [key: string]: any;
}) => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [data, setData] = useState<SelectProps['options']>([]);
  const handleSearch = async (newValue: string) => {
    const { data } = await patientSearch(peerServer, {
      search: newValue,
    });
    setData(data.data);
  };
  return (
    <Select
      {...rest}
      showSearch
      placeholder={placeholder}
      defaultActiveFirstOption={false}
      showArrow={false}
      filterOption={false}
      onSearch={handleSearch}
      notFoundContent={null}
      options={(data || []).map((d) => ({
        value: d.id,
        label: `${d.name}(${d.hospitalNumber})`,
      }))}
    />
  );
};
const VideoRecord = () => {
  const query = parse(location.search);
  const [_message, contextHolder] = message.useMessage();
  const { peerServer, panServer } = useModel('global');
  const [list, setList] = useState<RecordFile[]>([]);
  const [searchParams, setSearchParams] = useState<any>({ type: '0' });

  const loadFileList = () => {
    try {
      if (isBlank(searchParams.search)) {
        return;
      }
      videoRecordList(peerServer, searchParams).then(({ data }) => {
        if (data.success) {
          setList(data.data);
        }
      });
    } catch {
      _message.error('连接服务器失败');
    }
  };
  useEffect(loadFileList, [searchParams]);

  return (
    <div
      style={{
        userSelect: 'none',
        padding: '20px',
        height: '100%',
      }}
    >
      {contextHolder}
      <div
        style={{
          background: 'rgba(25, 38, 86, 0.9)',
          marginBlockEnd: '16px',
          borderRadius: '6px',
          height: '80px',
        }}
      >
        <QueryFilter<{
          search: string;
          searchTime: any;
          type: string;
        }>
          initialValues={{
            type: '0',
          }}
          // onFinish={async (params) => {
          //   // console.log(params);
          //   setSearchParams(params);
          // }}
          onValuesChange={(changedValues, allValues) => {
            // console.log(allValues);
            if (allValues.searchTime) {
              allValues.searchTime = allValues.searchTime.join(',');
            }
            setSearchParams((f: any) => ({ ...f, ...allValues }));
          }}
          submitter={{
            render: () => {
              return [
                <Button
                  key="refresh"
                  icon={<ReloadOutlined />}
                  onClick={() => loadFileList()}
                />,
              ];
            },
          }}
        >
          <ProFormItem label="患者" name="search" rules={[{ required: true }]}>
            <PatientSearch
              placeholder="搜索患者姓名/住院号"
              peerServer={peerServer}
            />
          </ProFormItem>
          <ProFormDateRangePicker name="searchTime" label="时间范围" />
          <ProFormRadio.Group
            name="type"
            label="类型"
            radioType="button"
            options={[
              {
                label: '录像',
                value: '0',
              },
              {
                label: '截图',
                value: '1',
              },
            ]}
          />
        </QueryFilter>
      </div>
      <div
        style={{
          background: 'rgba(25, 38, 86, 0.9)',
          height: 'calc(100% - 96px)',
          borderRadius: '6px',
          overflowY: 'auto',
        }}
      >
        <Row gutter={[16, 16]} className={styles.fileList}>
          {list.map((d) => (
            <Col key={d.fileName} xl={6} xxl={4}>
              <div className={styles.file}>
                <div
                  className={styles.fileImage}
                  onClick={() => {
                    if (searchParams.type === '0') {
                      console.log('d.fileUrl', d.fileUrl);
                      window.tm?.ipcRenderer.send(
                        'previewVideo',
                        `${d.fileUrl.replaceAll('/mp4', '')}`,
                        d.fileName,
                      );
                    }
                  }}
                >
                  {searchParams.type === '0' && (
                    <img className={styles.imgIcon} src="/img/video.svg" />
                  )}
                  {searchParams.type === '1' && (
                    <Image
                      width="100%"
                      src={d.fileUrl}
                      preview={{ maskClassName: styles.previewImg }}
                    />
                  )}
                </div>
                <div className={styles.fileToolBar}>
                  <div className={styles.btnGroup}>
                    {query.role === 'admin' && (
                      <Popconfirm
                        key="delete"
                        title="确认删除吗？"
                        onConfirm={async () => {
                          const { data, success } = await deleteRecordFile(
                            peerServer,
                            d.id,
                            searchParams.type,
                          );
                          if (success) {
                            loadFileList();
                            _message.success('删除成功');
                          } else {
                            _message.error('删除失败');
                          }
                        }}
                      >
                        <Button
                          className={styles.deleteBtn}
                          type="primary"
                          icon={<DeleteOutlined />}
                        />
                      </Popconfirm>
                    )}
                    <Button
                      className={styles.downloadBtn}
                      type="primary"
                      icon={<DownloadOutlined />}
                      onClick={() => {
                        // window.open(`${panServer}${d.fileUrl}`, '_blank');
                        const link = document.createElement('a');
                        link.style.display = 'none';
                        link.href = `${d.fileUrl}`;
                        // link.href = `${panServer}${d.fileUrl}`;
                        link.setAttribute('download', d.fileName);
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                      }}
                    />
                  </div>
                </div>
                <div className={styles.fileTitle}>{d.fileName}</div>
              </div>
            </Col>
          ))}
        </Row>
      </div>
    </div>
  );
};

export default VideoRecord;
